import axios from "axios";
import { ElMessage } from "element-plus";
// import { useUserKey } from "@/store/user";
import { relogin } from "@/common";
const instance = axios.create({
  baseURL: "/api",
  timeout: 5000,
});

instance.interceptors.request.use(
  (config) => {
    let token = localStorage.getItem("token");
    if (token) {
      if (config.headers) {
        config.headers["Authorization"] = token;
      }
    }
    return config;
  },
  (err) => Promise.reject(err)
);

instance.interceptors.response.use(
  (response) => {
    const data = response.data as IResponse<any>;
    // const userStore = useUserKey();
    if (data.code === 401) {
      // 401代表token过期了
      // 让用户重新登录与退出登录是一样的
      relogin(
        () => {},
        () => {
          ElMessage.error("登录凭证失败，请重新登录");
        }
      );
      // 提示
    } else if (data.code !== 200) {
      ElMessage.error(data.message);
    }
    return response.data;
  },
  (err) => {
    ElMessage.error("请求失败，错误信息：" + err.message);
    Promise.reject(err);
  }
);

export default instance;
